//
//  KmlElementDB.m
//  Tazama NGO
//
//  Created by jsheriff on 5/31/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "KmlElementDB.h"
#import "Notifications.h"
#import "Settings.h"

@interface KmlElementDB () 

@property (nonatomic, assign) BOOL  waitingForKmlToLoad;

-(void)readFromKmlFeed:(NSTimer*)timer;

@end

@implementation KmlElementDB

@synthesize kmlAnnotationList;
@synthesize kmlOverlayList;
@synthesize waitingForKmlToLoad;
@synthesize kmlParser;

static KmlElementDB *sharedInstance = nil;

+ (KmlElementDB *)sharedInstance
{
    if (sharedInstance == nil) {
        sharedInstance = [[super allocWithZone:NULL] init];
    }
    return sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [[self sharedInstance] retain];
}

- (id)init
{
    if ((self = [super init]))
	{
		kmlAnnotationList = [[NSArray alloc] init];
        kmlOverlayList = [[NSArray alloc] init];
        waitingForKmlToLoad = NO;
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}

- (oneway void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}

-(void)startPollingFeed {
    [self readFromKmlFeed:nil];
    
    // Get the update period
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    int updatePeriodKey = [[defaults valueForKey:kKmlFeedUpdatePeriod] intValue];
    double updatePeriod = updatePeriodKey;
    /*
    double updatePeriod = 120.0;
    if (updatePeriodKey == 0) {
        updatePeriod = 30.0;
    }
    else if (updatePeriodKey == 1) {
        updatePeriod = 60.0;
    }
    else if (updatePeriodKey == 2) {
        updatePeriod = 120.0;
    }*/

    
    NSTimer *newTimer = [[NSTimer scheduledTimerWithTimeInterval:updatePeriod target:self selector:@selector(readFromKmlFeed:) userInfo:nil repeats:YES] retain];
    timer = newTimer;
}
-(void)stopPollingFeed {
    [timer invalidate];
    [timer release];
    timer = nil;
}

- (void)readFeedNow {
    [self readFromKmlFeed:nil];
}

- (void)readKmlFeedDidFinish:(KMLParser *)newKml {
    [kmlParser release];
    kmlParser = newKml;
    
    // Add all of the MKOverlay objects parsed from the KML file to the map.
    kmlOverlayList = [kmlParser overlays];
    
    // Add all of the MKAnnotation objects parsed from the KML file to the map.
    kmlAnnotationList = [kmlParser points];
    
    waitingForKmlToLoad = NO;
    
    NSLog(@"Finished reading data from KML feed, %d annotations, %d overlays", [kmlAnnotationList count], [kmlOverlayList count]);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kKmlDatabaseUpdateKey object:self userInfo:nil];
}

-(void)readFromKmlFeed:(NSTimer *)timer
{
    // Make sure that we've finished the last KML request
    if (waitingForKmlToLoad) {
        NSLog(@"Unable to read KML data, still waiting for previous request");
        return;
    }
    
    // Get the host name
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    /*
    NSString *hostName = [defaults stringForKey:kHostName];
    if (hostName == nil || hostName.length == 0)
    {
        NSLog(@"Unable to read KML feed, host name not found");
        return;
    }

    waitingForKmlToLoad = YES;
    NSString *urlStr;
    if ([defaults objectForKey:kPort]) {
        if ([hostName rangeOfString:@"http://"].location == NSNotFound) {
            urlStr = [NSString stringWithFormat:@"http://%@:%@/feeds/all/kml", hostName, [defaults objectForKey:kPort]];
        }
        else {
            urlStr = [NSString stringWithFormat:@"%@:%@/feeds/all/kml", hostName, [defaults objectForKey:kPort]];
        }
    }
    else {
        if ([hostName rangeOfString:@"http://"].location == NSNotFound) {
            urlStr = [NSString stringWithFormat:@"http://%@/feeds/all/kml", hostName];
        }
        else {
            urlStr = [NSString stringWithFormat:@"%@/feeds/all/kml", hostName];
        }
    }
    */
    NSString *urlStr = [defaults stringForKey:feedURL];
    if (urlStr == nil || urlStr.length == 0) {
        NSLog(@"Unable to read KML feed url. URL not found");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Data Feed Not Found" message:@"Please enter a proper data feed URL in settings" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSLog(@"Requesting data from KML feed (%@)", [url absoluteString]);
    
    // Load the KML data using GCD
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        KMLParser *newKml = [[KMLParser parseKMLAtURL:url] retain];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self readKmlFeedDidFinish:newKml];
        });
    });
}

- (MKAnnotationView *)viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKAnnotationView *annotationView = [kmlParser viewForAnnotation:annotation];
    
    // scale icon if neccessary
    if (annotationView.image.size.height > 40 || annotationView.image.size.width > 40) {
        annotationView.contentMode = UIViewContentModeScaleAspectFit;
        annotationView.frame = CGRectMake(0, 0, 35, 35);
    }
    
    return annotationView;
}

@end
